package cn.huiyunche.admin.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.alibaba.fastjson.JSONObject;

import cn.huiyunche.base.service.framework.utils.AppUtils;
import cn.huiyunche.base.service.vo.AdminUserVo;

/**
 * 认证成功需要向前台返回jwt.
 *
 * @author zhaoshb
 * @since 0.0.1
 *
 */
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	private String secureKey = null;

	public JwtAuthenticationSuccessHandler(String secureKey) {
		this.secureKey = secureKey;
	}

	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		User u = (User) authentication.getPrincipal();
		AdminUserVo user = new AdminUserVo(u.getUsername(), u.getPassword(), true);
		// user.setId(u.getId());
		String token = JwtUtils.generateToken(user, this.getSecureKey());

		JSONObject jsonObject = AppUtils.generateSuccessJson();
		jsonObject.put(JwtAuthenicationFilter.HEADER_AUTHORIZATION, JwtAuthenicationFilter.PREFIX_AUTHORIZATION + token);

		AppUtils.responseJson(response, jsonObject);
	}

	public void setSecureKey(String secureKey) {
		this.secureKey = secureKey;
	}

	private String getSecureKey() {
		return this.secureKey;
	}
}
